<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;

/**
 * 店铺名称管理
 *
 * @icon fa fa-circle-o
 */
class Feditionchart extends Backend
{
    
    /**
     * Feditionaccounturl模型对象
     * @var \app\admin\model\Feditionaccounturl
     */
    protected $model = null;
    protected $admin = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->view->assign("timeList", $this->getStatusList());
//        $this->auth->id = 6;
        $this->admin = Db::name('admin')->where('id', '=', $this->auth->id)->find();
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }

        $where['status'] = 'normal';
        $row['single_quantity'] = Db::name('fedition_report')->where($where)->sum('single_quantity');
        $row['amount'] = Db::name('fedition_report')->where($where)->sum('amount');
        $row['advertising'] = Db::name('fedition_report')->where($where)->sum('advertising');
        $row['sales'] = Db::name('fedition_report')->where($where)->sum('sales');
        $this->view->assign("row", $row);
        $usatime = date('Y-m-d H:i:s',time() - 12*3600);
        $this->view->assign("usatime", $usatime);
        $this->view->assign("admin", $this->admin);
        $arr_admin = array();
        if($this->admin['report_auth'] == 1){
            $arr_admin = Db::name('admin')
//                ->where('status','normal')
                ->where('launch','1')
                ->select();
        }
        $this->view->assign("arr_admin", $arr_admin);
//        默认七天搜索
        $begintime = date('Y-m-d 00:00:00', strtotime("-6 day"));
        $endtime= date('Y-m-d H:i:s',mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1);
        $time_ranking = $begintime.' - '.$endtime;
        $this->view->assign("time_ranking", $time_ranking);
        return $this->view->fetch();
    }

    /**
     * getStatusList
     */
    public function getStatusList()
    {
        return ['1' => __('今天'),
            '2' => __('昨天'),
            '3' => __('最近七天'),
            '4' => __('最近三十天'),
            '5' => __('本月'),
            '6' => __('上月'),
        ];
    }

    /**
     * ajax_statistics
     */
    public function ajax_statistics()
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $example_times = $this->request->post("example_times");
        $time = $this->request->post("time");
        $admin_id = $this->request->post("admin_id");
        //$time优先级最高
        if(!empty($time)){
            $wheretime = $this->example_times($time,1,'timedate');
        }else{
            $wheretime = $this->example_times($example_times,2,'timedate');
        }
        //根据日期按天排序，再根据类型字段排序
        if($this->admin['report_auth'] == 0){
            //只查看自己的数据
            $where = 'and admin_id = '.$this->admin['id'];
            $sql = "SELECT SUM(advertising) as advertisingz,SUM(sales) as salesz,SUM(single_quantity) as single_quantityz FROM fa_fedition_report WHERE ".$wheretime." ".$where;
        }else{
            if($admin_id == 0){
                $sql = "SELECT SUM(advertising) as advertisingz,SUM(sales) as salesz,SUM(single_quantity) as single_quantityz FROM fa_fedition_report WHERE ".$wheretime;
            }else{
                //只查看自己的数据
                $where = 'and admin_id = '.$admin_id;
                $sql = "SELECT SUM(advertising) as advertisingz,SUM(sales) as salesz,SUM(single_quantity) as single_quantityz FROM fa_fedition_report WHERE ".$wheretime." ".$where;
            }
        }
        $statistics = \think\Db::query($sql);
        $statisticsz = $statistics[0];
        //API接口数据覆盖
        //$time优先级最高
        if(!empty($time)){
            $wheretime2 = $this->example_times($time,1,'daystamp');
        }else{
            $wheretime2 = $this->example_times($example_times,2,'daystamp');
        }
        //根据日期按天排序，再根据类型字段排序
        if($this->admin['report_auth'] == 0){
            //只查看自己的数据
            $where = 'and admin_id = '.$this->admin['id'];
            $sql = "SELECT accounturl,sum(orders) as single_quantityz,cast(sum(sum) AS decimal(15,2)) as salesz,b.admin_id FROM fa_fedition_statisticsshopify as a LEFT JOIN fa_fedition_accounturl as b ON a.accounturl=b.id WHERE ".$wheretime2." ".$where;
        }else{
            if($admin_id == 0){
                $sql = "SELECT accounturl,sum(orders) as single_quantityz,cast(sum(sum) AS decimal(15,2)) as salesz,b.admin_id FROM fa_fedition_statisticsshopify as a LEFT JOIN fa_fedition_accounturl as b ON a.accounturl=b.id WHERE ".$wheretime2;
            }else{
                //只查看自己的数据
                $where = 'and admin_id = '.$admin_id;
                $sql = "SELECT accounturl,sum(orders) as single_quantityz,cast(sum(sum) AS decimal(15,2)) as salesz,b.admin_id FROM fa_fedition_statisticsshopify as a LEFT JOIN fa_fedition_accounturl as b ON a.accounturl=b.id WHERE ".$wheretime2." ".$where;
            }
        }
        $statistics2 = \think\Db::query($sql);
        if(!empty($statistics2[0]['salesz'])){
            if(isset($statisticsz['salesz'])){
                $statisticsz['oldsalesz'] = $statisticsz['salesz'];
            }
            $statisticsz['salesz'] = $statistics2[0]['salesz'];
        }
        if(!empty($statistics2[0]['single_quantityz'])){
            if(isset($statisticsz['single_quantityz'])){
                $statisticsz['oldsingle_quantityz'] = $statisticsz['single_quantityz'];
            }
            $statisticsz['single_quantityz'] = $statistics2[0]['single_quantityz'];
        }
//        重新算roi
        if(!empty($statisticsz['advertisingz']) && !empty($statisticsz['salesz'])){
            $statisticsz['roi'] = '1:'.number_format((float)$statisticsz['salesz'] / $statisticsz['advertisingz'], 2);
        }else{
            $statisticsz['roi'] = '0';
        }

//        $statisticsz['usatimes'] = '';
//        if(!empty($time)){
//            $explode_usatime = explode(' - ',$time);
//            date_default_timezone_set('Asia/Shanghai');
//            $usatimes = date('Y-m-d H:i:s',strtotime($explode_usatime[0]) - 12*3600).' - '.date('Y-m-d H:i:s',strtotime($explode_usatime[1]) - 12*3600);
//            $statisticsz['usatimes'] = $usatimes;
//        }
        $this->success('返回数据','', $statisticsz);
    }

    /**
     * ajax_sales
     */
    public function ajax_sales()
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $example_times = $this->request->post("example_times");
        $time = $this->request->post("time");
        $admin_id = $this->request->post("admin_id");
        //$time优先级最高
        if(!empty($time)){
            $wheretime = $this->example_times($time,1,'timedate');
        }else{
            $wheretime = $this->example_times($example_times,2,'timedate');
        }
        //根据日期按天排序，再根据类型字段排序
        if($this->admin['report_auth'] == 0){
            //只查看自己的数据
            $where = 'and admin_id = '.$this->admin['id'];
            $sql = "SELECT FROM_UNIXTIME(timedate,'%m-%d') as timedate,SUM(advertising) as advertisingz,SUM(sales) as salesz,SUM(single_quantity) as single_quantityz FROM fa_fedition_report WHERE ".$wheretime." ".$where." GROUP BY timedate";
        }else{
            if($admin_id == 0){
                $sql = "SELECT FROM_UNIXTIME(timedate,'%m-%d') as timedate,SUM(advertising) as advertisingz,SUM(sales) as salesz,SUM(single_quantity) as single_quantityz FROM fa_fedition_report WHERE ".$wheretime." GROUP BY timedate";
            }else{
                //只查看自己的数据
                $where = 'and admin_id = '.$admin_id;
                $sql = "SELECT FROM_UNIXTIME(timedate,'%m-%d') as timedate,SUM(advertising) as advertisingz,SUM(sales) as salesz,SUM(single_quantity) as single_quantityz FROM fa_fedition_report WHERE ".$wheretime." ".$where." GROUP BY timedate";
            }
        }
        $statistics = \think\Db::query($sql);
        $return = array();
        $return['arrtitle'] = ['销售总金额', '广告消耗', '订单量'];
        if($statistics){
            $arrtimedate = array();
            $arradvertisingz = array();
            $arrsalesz = array();
            $arrsingle_quantityz = array();
            foreach ($statistics as $k => $v) {
                $arrtimedate[] = $v['timedate'];
                $arradvertisingz[] = $v['advertisingz'];
                $arrsalesz[] = $v['salesz'];
                $arrsingle_quantityz[] = $v['single_quantityz'];
            }
            $return['arrtimedate'] = $arrtimedate;
            $return['arradvertisingz'] = $arradvertisingz;
            $return['arrsalesz'] = $arrsalesz;
            $return['arrsingle_quantityz'] = $arrsingle_quantityz;
        }
        //API接口数据覆盖
        //$time优先级最高
        if(!empty($time)){
            $wheretime2 = $this->example_times($time,1,'daystamp');
        }else{
            $wheretime2 = $this->example_times($example_times,2,'daystamp');
        }
        //根据日期按天排序，再根据类型字段排序
        if($this->admin['report_auth'] == 0){
            //只查看自己的数据
            $where = 'and admin_id = '.$this->admin['id'];
            $sql = "SELECT cast(sum(sum) AS decimal(15,2)) as salesz,day as timedate ,b.admin_id FROM fa_fedition_statisticsshopify as a LEFT JOIN fa_fedition_accounturl as b ON a.accounturl=b.id WHERE ".$wheretime2." ".$where." GROUP BY day";
        }else{
            if($admin_id == 0){
                $sql = "SELECT cast(sum(sum) AS decimal(15,2)) as salesz,day as timedate FROM fa_fedition_statisticsshopify WHERE ".$wheretime2." GROUP BY day";
            }else{
                //只查看自己的数据
                $where = 'and admin_id = '.$admin_id;
                $sql = "SELECT cast(sum(sum) AS decimal(15,2)) as salesz,day as timedate ,b.admin_id FROM fa_fedition_statisticsshopify as a LEFT JOIN fa_fedition_accounturl as b ON a.accounturl=b.id WHERE ".$wheretime2." ".$where." GROUP BY day";
            }
        }
        $statistics2 = \think\Db::query($sql);
        $arrsalesz2 = array();
        $arrtimedate2 = array();
        if(!empty($statistics2)){
            foreach ($statistics2 as $k => $v) {
                $arrtimedate2[] = $v['timedate'];
                $arrsalesz2[] = $v['salesz'];
            }
            if(isset($return['arrsalesz'])){
                $return['oldarrsalesz'] = $return['arrsalesz'];
            }
            if(isset($return['arrtimedate'])){
                $return['oldarrtimedate'] = $return['arrtimedate'];
            }
            $return['arrsalesz'] = $arrsalesz2;
            $return['arrtimedate'] = $arrtimedate2;
        }
        $this->success('返回数据','', $return);
    }

    /**
     * ajax_ranking
     */
    public function ajax_ranking()
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $example_times = $this->request->post("example_times");
        $time = $this->request->post("time");
        //API接口数据覆盖
        //$time优先级最高
        if(!empty($time)){
            $wheretime2 = $this->example_times($time,1,'daystamp');
        }else{
            $wheretime2 = $this->example_times($example_times,2,'daystamp');
        }
        //根据日期按天排序，再根据类型字段排序
        $statistics = array();
        if($this->admin['report_auth'] == 0){

        }else{
            $sql = "SELECT daystamp,day,gateway,accounturl,cast(sum(sum) AS decimal(15,2)) as salesz,b.admin_id ,c.nickname 
FROM fa_fedition_statisticsshopify as a 
LEFT JOIN fa_fedition_accounturl as b ON a.accounturl=b.id 
LEFT JOIN fa_admin as c ON b.admin_id=c.id 
WHERE ".$wheretime2."
GROUP BY daystamp,b.admin_id
ORDER BY daystamp ASC";
            $statistics = \think\Db::query($sql);
        }
        if(!empty($statistics)){
            foreach($statistics as $v){
                $newstatistics[$v['day']][]=$v;
            }
            foreach ($newstatistics as $k => $v) {
                $newdate = array();
                foreach ($v as $key => $val){
                    if($k == $val['day']){
                        $newdate[$val['admin_id']][]=$val;
                    }
                }
                $admins = array();
                foreach ($newdate as $kn => $vn) {
                    $adminsalesz = 0;
                    foreach ($vn as $kn1 => $vn1){
                        $adminsalesz += $vn1['salesz'];
                    }
                    $admins[$kn] = round($adminsalesz,2);
                }
                $newadminarr[$k] = $admins;
            }
            $arr_admin = Db::name('admin')
                ->where('launch','1')
                ->order('id asc')
                ->select();
            $arr_name = array();
            foreach ($arr_admin as $ka => $va) {
                $arr_id[$va['id']] = 0;
                $arr_name[] = $va['nickname'];
            }
            $arr_admin_id = $arr_id;
            $date = array();
            foreach ($newadminarr as $k => $v) {
                $arr_id = $arr_admin_id;
                foreach ($v as $kv => $vv) {
                    $arr_id[$kv] = $vv;
                }
                $newadminarr[$k] = $arr_id;
                $date[] = $k;
            }
            foreach ($newadminarr as $k => $v) {
                foreach ($v as $kv => $vv) {
                    $arrangement[$kv][] = $vv;
                }
            }
            foreach ($arr_admin_id as $k => $v) {
                $newadmin[] = $arrangement[$k];
            }
            //接入报表数据
//            $arr_nameyf = array();
//            foreach ($date as $k => $v) {
//                $admin_yf = Db::name('fedition_report')
//                    ->where('admin_id',8)
//                    ->where('timedate',strtotime($v))
//                    ->find();
//                if(!empty($admin_yf)){
//                    $arr_nameyf[] = $admin_yf['sales'];
//                }else{
//                    $arr_nameyf[] = 0;
//                }
//            }
//            $newadmin[3] = $arr_nameyf;

            $statisticsz['date'] = $date;
            $statisticsz['name'] = $arr_name;
            $statisticsz['newadmin'] = $newadmin;
            $this->success('返回数据','', $statisticsz);
        }else{
            $statisticsz['date'] = array();
            $statisticsz['name'] =array();
            $statisticsz['newadmin'] = array();
            $this->success('返回数据','', $statisticsz);
        }
    }

    /**
     * example_times
     */
    public function example_times($example_times,$type,$timedate)
    {
        if($type == 1){
            $explode_times = explode(' - ',$example_times);
            $times = $timedate.'>='.strtotime($explode_times[0]).' and '.$timedate.'<='.strtotime($explode_times[1]);
        }elseif ($type == 2){
            switch ($example_times)
            {
//                全部
                case 0:
                    $times = '1=1';
                    break;
//                今日
                case 1:
                    $beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));
                    $endToday=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
                    $times = $timedate.'>='.$beginToday.' and '.$timedate.'<='.$endToday;
                    break;
//                昨日
                case 2:
                    $beginYesterday=mktime(0,0,0,date('m'),date('d')-1,date('Y'));
                    $endYesterday=mktime(0,0,0,date('m'),date('d'),date('Y'))-1;
                    $times = $timedate.'>='.$beginYesterday.' and '.$timedate.'<='.$endYesterday;
                    break;
//                最近七天
                case 3:
                    $begintime = strtotime(date('Y-m-d 00:00:00', strtotime("-6 day")));
                    $endtime=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
                    $times = $timedate.'>='.$begintime.' and '.$timedate.'<='.$endtime;
                    break;
//                最近三十天
                case 4:
                    $begintime = strtotime(date('Y-m-d 00:00:00', strtotime("-29 day")));
                    $endtime=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
                    $times = $timedate.'>='.$begintime.' and '.$timedate.'<='.$endtime;
                    break;
//                本月
                case 5:
                    $beginThismonth=mktime(0,0,0,date('m'),1,date('Y'));
                    $endThismonth=mktime(23,59,59,date('m'),date('t'),date('Y'));
                    $times = $timedate.'>='.$beginThismonth.' and '.$timedate.'<='.$endThismonth;
                    break;
//                上个月
                case 6:
                    $lastmonth_start=mktime(0,0,0,date('m')-1,1,date('Y'));
                    $lastmonth_end=mktime(23,59,59,date('m'),0,date('Y'));
                    $times = $timedate.'>='.$lastmonth_start.' and '.$timedate.'<='.$lastmonth_end;
                    break;
                default:
                    $times = '1=1';
            }
        }else{
            $times = '1=1';
        }

        return $times;
    }
}
